/*
 *    Copyright 2008-2009 The PoCo Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.asemantics.poco.converters;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.AbstractConverter;

import com.asemantics.poco.DateTime;

/**
 * 
 * @author Simone Tripodi
 * @version $Id: DateTimeConverter.java 239 2009-12-20 00:12:56Z simone.tripodi@gmail.com $
 */
@SuppressWarnings("unchecked")
public final class DateTimeConverter extends AbstractConverter {

    private final static Pattern DATETIME_PATTERN =
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})([zZ]|[\\+-]\\d{2}:\\d{2})?");

    private final static SimpleDateFormat ISODATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");

    public DateTimeConverter() {
        this(null);
    }

    public DateTimeConverter(Object defaultValue) {
        super(defaultValue);
    }

    @Override
    protected Object convertToType(Class type, Object value) throws Throwable {
        String stringValue = value.toString();
        Matcher matcher = DATETIME_PATTERN.matcher(stringValue);
        if (!matcher.matches()) {
            throw new ConversionException("Input string ["
                    + stringValue
                    + "] doesn't match with xsd:dateTime pattern");
        }

        Date date = null;

        String dateString = matcher.group(1);
        try {
            date = ISODATE_FORMAT.parse(dateString);
        } catch (ParseException e) {
            throw new ConversionException("Date part ["
                    + dateString
                    + "] doesn't match with xsd:dateTime pattern");
        }

        String timeZoneString = matcher.group(2);
        if (timeZoneString == null) {
            return new DateTime(date);
        }

        return new DateTime(date, (TimeZone) ConvertUtils.convert(timeZoneString, TimeZone.class));
    }

    @Override
    protected String convertToString(Object value) throws Throwable {
        DateTime dateTime = (DateTime) value;
        StringBuilder builder =
            new StringBuilder(ISODATE_FORMAT.format(dateTime.getDate()));
        builder.append(ConvertUtils.convert(dateTime.getTimeZone(), String.class));
        return builder.toString();
    }

    @Override
    protected Class getDefaultType() {
        return DateTime.class;
    }

}
